﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Core.Service;
using Microsoft.AspNetCore.Http;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;

namespace Admin.NET.Application;

/// <summary>
/// 球队管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class AppTeamService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<AppTeam> _appTeamRep;
    private readonly SysFileService _sysFileService;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly UserManager _userManager;
    private readonly AppTeamPlayerApplyService _appTeamPlayerApplyService;

    public AppTeamService(SqlSugarRepository<AppTeam> appTeamRep, SysFileService sysFileService, ISqlSugarClient sqlSugarClient,
        UserManager userManager, AppTeamPlayerApplyService appTeamPlayerApplyService)
    {
        _appTeamRep = appTeamRep;
        _sysFileService = sysFileService;
        _sqlSugarClient = sqlSugarClient;
        _userManager = userManager;
        _appTeamPlayerApplyService = appTeamPlayerApplyService;

    }

    /// <summary>
    /// 分页查询球队管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询球队管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<AppTeamOutput>> Page(PageAppTeamInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appTeamRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.Name.Contains(input.Keyword) || u.Slogan.Contains(input.Keyword) || u.Avatar.Contains(input.Keyword) || u.ProvinceCode.Contains(input.Keyword) || u.DistrictCode.Contains(input.Keyword) || u.CityCode.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TeamName), u => u.Name.Contains(input.TeamName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Slogan), u => u.Slogan.Contains(input.Slogan.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Avatar), u => u.Avatar.Contains(input.Avatar.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProvinceCode), u => u.ProvinceCode.Contains(input.ProvinceCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DistrictCode), u => u.DistrictCode.Contains(input.DistrictCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.CityCode), u => u.CityCode.Contains(input.CityCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.Level != null, u => u.Level == input.Level)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Type), u => u.Type == input.Type)
            .WhereIF(input.DirectorId != null, u => u.DirectorId == input.DirectorId)
            .WhereIF(input.Status.HasValue, u => u.Status == input.Status)
            .LeftJoin<SysRegion>((u, provinceCode) => u.ProvinceCode == provinceCode.Code)
            .LeftJoin<SysRegion>((u, provinceCode, districtCode) => u.DistrictCode == districtCode.Code)
            .LeftJoin<SysRegion>((u, provinceCode, districtCode, cityCode) => u.CityCode == cityCode.Code)
            .LeftJoin<SysUser>((u, provinceCode, districtCode, cityCode, director) => u.DirectorId == director.Id)
            .Select((u, provinceCode, districtCode, cityCode, director) => new AppTeamOutput
            {
                Id = u.Id,
                Name = u.Name,
                Slogan = u.Slogan,
                Avatar = u.Avatar,
                ProvinceCode = u.ProvinceCode,
                ProvinceCodeFkDisplayName = $"{provinceCode.Name}",
                DistrictCode = u.DistrictCode,
                DistrictCodeFkDisplayName = $"{districtCode.Name}",
                CityCode = u.CityCode,
                CityCodeFkDisplayName = $"{cityCode.Name}",
                RegionId = u.RegionId,
                Code = u.Code,
                Level = u.Level,
                Type = u.Type,
                DirectorId = u.DirectorId,
                DirectorFkDisplayName = $"{director.RealName}",
                OrderNo = u.OrderNo,
                Status = u.Status,
                Remark = u.Remark,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取球队管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取球队管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<AppTeamOutput> Detail([FromQuery] QueryByIdAppTeamInput input)
    {
        var result= await _appTeamRep.AsQueryable().Where(u => u.Id == input.Id)
            .Select(u=> new AppTeamOutput
            {
                Users = SqlFunc.Subqueryable<AppUserTeam>()
                                    .LeftJoin<SysUser>((aut,su)=>aut.UserId==su.Id)
                                    .Where(aut => aut.TeamId==u.Id && aut.IsDelete==false&& aut.Status== StatusEnum.Enable)
                                    .ToList((aut, su)=> new UserBaseOutput
                                    {
                                        Id=su.Id,

                                    },true)
            },true).FirstAsync()
            ;
        return result;
    }

    /// <summary>
    /// 增加球队管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加球队管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddAppTeamInput input)
    {
        var entity = input.Adapt<AppTeam>();
        var result = await _appTeamRep.InsertAsync(entity) ? entity.Id : 0;
        await _appTeamRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().InsertAsync(new AppUserTeam
        {
            UserId = _userManager.UserId,
            TeamId = result,
            Role = TeamRoleEnum.Captain,
            Position = PlayerPositionEnum.Goalkeeper,
            JoinDate = DateTime.Now,
        });
        //增加申请表
        await _appTeamPlayerApplyService.Add(new AddAppTeamPlayerApplyInput
        {
            Type = TeamPlayerEnum.Team,
            UserId = _userManager.UserId,
            TeamId = result,
            ApplicationDate = DateTime.Now,
        });
        return result;
    }

    /// <summary>
    /// 更新球队管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新球队管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateAppTeamInput input)
    {
        var entity = input.Adapt<AppTeam>();
        await _appTeamRep.AsUpdateable(entity)
        .IgnoreColumns(u => new {
            u.RegionId,
            u.Code,
            u.OrderNo,
        })
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除球队管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除球队管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteAppTeamInput input)
    {
        var entity = await _appTeamRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _appTeamRep.FakeDeleteAsync(entity);   //假删除
        var userTeamEntitys = await _appTeamRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().GetListAsync(u => u.TeamId == input.Id);
        await _appTeamRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().FakeDeleteAsync(userTeamEntitys);
        //await _appTeamRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除球队管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除球队管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")] List<DeleteAppTeamInput> input)
    {
        var exp = Expressionable.Create<AppTeam>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _appTeamRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
        var result = await _appTeamRep.FakeDeleteAsync(list);   //假删除
        var userTeamEntitys = await _appTeamRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().GetListAsync(u => input.Select(u => u.Id).Contains(u.TeamId));
        await _appTeamRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().FakeDeleteAsync(userTeamEntitys);
        return result;
        //return await _appTeamRep.DeleteAsync(list);   //真删除
    }

    /// <summary>
    /// 设置球队管理状态 🚫
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("设置球队管理状态")]
    [ApiDescriptionSettings(Name = "SetStatus"), HttpPost]
    public async Task SetAppTeamStatus(SetAppTeamStatusInput input)
    {
        await _appTeamRep.AsUpdateable().SetColumns(u => u.Status, input.Status).Where(u => u.Id == input.Id).ExecuteCommandAsync();
    }

    /// <summary>
    /// 上传队徽 ⬆️
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [DisplayName("上传队徽")]
    [ApiDescriptionSettings(Name = "UploadAvatar"), HttpPost]
    public async Task<SysFile> UploadAvatar([Required] IFormFile file)
    {
        return await _sysFileService.UploadFile(new UploadFileInput { File = file, SavePath = "upload/team-avatar" });
    }

    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataAppTeamInput input)
    {
        var provinceCodeData = await _appTeamRep.Context.Queryable<SysRegion>()
            .InnerJoinIF<AppTeam>(input.FromPage, (u, r) => u.Code == r.ProvinceCode)
            .Select(u => new {
                Value = u.Code,
                Label = $"{u.Name}"
            }).ToListAsync();
        var districtCodeData = await _appTeamRep.Context.Queryable<SysRegion>()
            .InnerJoinIF<AppTeam>(input.FromPage, (u, r) => u.Code == r.DistrictCode)
            .Select(u => new {
                Value = u.Code,
                Label = $"{u.Name}"
            }).ToListAsync();
        var cityCodeData = await _appTeamRep.Context.Queryable<SysRegion>()
            .InnerJoinIF<AppTeam>(input.FromPage, (u, r) => u.Code == r.CityCode)
            .Select(u => new {
                Value = u.Code,
                Label = $"{u.Name}"
            }).ToListAsync();
        var directorIdData = await _appTeamRep.Context.Queryable<SysUser>()
            .InnerJoinIF<AppTeam>(input.FromPage, (u, r) => u.Id == r.DirectorId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.RealName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "provinceCode", provinceCodeData },
            { "districtCode", districtCodeData },
            { "cityCode", cityCodeData },
            { "directorId", directorIdData },
        };
    }

    /// <summary>
    /// 导出球队管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出球队管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageAppTeamInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportAppTeamOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "球队管理导出记录");
    }

    /// <summary>
    /// 下载球队管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载球队管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportAppTeamOutput>(), "球队管理导入模板", (_, info) =>
        {
            if (nameof(ExportAppTeamOutput.ProvinceCodeFkDisplayName) == info.Name) return _appTeamRep.Context.Queryable<SysRegion>().Select(u => $"{u.Name}").Distinct().ToList();
            if (nameof(ExportAppTeamOutput.DistrictCodeFkDisplayName) == info.Name) return _appTeamRep.Context.Queryable<SysRegion>().Select(u => $"{u.Name}").Distinct().ToList();
            if (nameof(ExportAppTeamOutput.CityCodeFkDisplayName) == info.Name) return _appTeamRep.Context.Queryable<SysRegion>().Select(u => $"{u.Name}").Distinct().ToList();
            if (nameof(ExportAppTeamOutput.DirectorFkDisplayName) == info.Name) return _appTeamRep.Context.Queryable<SysUser>().Select(u => $"{u.RealName}").Distinct().ToList();
            return null;
        });
    }

    /// <summary>
    /// 导入球队管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入球队管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportAppTeamInput, AppTeam>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 省份
                    var provinceCodeLabelList = pageItems.Where(x => x.ProvinceCodeFkDisplayName != null).Select(x => x.ProvinceCodeFkDisplayName).Distinct().ToList();
                    if (provinceCodeLabelList.Any())
                    {
                        var provinceCodeLinkMap = _appTeamRep.Context.Queryable<SysRegion>().Where(u => provinceCodeLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Code);
                        pageItems.ForEach(e => {
                            e.ProvinceCode = provinceCodeLinkMap.GetValueOrDefault(e.ProvinceCodeFkDisplayName ?? "");
                            if (e.ProvinceCode == null) e.Error = "省份链接失败";
                        });
                    }
                    // 链接 区
                    var districtCodeLabelList = pageItems.Where(x => x.DistrictCodeFkDisplayName != null).Select(x => x.DistrictCodeFkDisplayName).Distinct().ToList();
                    if (districtCodeLabelList.Any())
                    {
                        var districtCodeLinkMap = _appTeamRep.Context.Queryable<SysRegion>().Where(u => districtCodeLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Code);
                        pageItems.ForEach(e => {
                            e.DistrictCode = districtCodeLinkMap.GetValueOrDefault(e.DistrictCodeFkDisplayName ?? "");
                            if (e.DistrictCode == null) e.Error = "区链接失败";
                        });
                    }
                    // 链接 市
                    var cityCodeLabelList = pageItems.Where(x => x.CityCodeFkDisplayName != null).Select(x => x.CityCodeFkDisplayName).Distinct().ToList();
                    if (cityCodeLabelList.Any())
                    {
                        var cityCodeLinkMap = _appTeamRep.Context.Queryable<SysRegion>().Where(u => cityCodeLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Code);
                        pageItems.ForEach(e => {
                            e.CityCode = cityCodeLinkMap.GetValueOrDefault(e.CityCodeFkDisplayName ?? "");
                            if (e.CityCode == null) e.Error = "市链接失败";
                        });
                    }
                    // 链接 负责人Id
                    var directorIdLabelList = pageItems.Where(x => x.DirectorFkDisplayName != null).Select(x => x.DirectorFkDisplayName).Distinct().ToList();
                    if (directorIdLabelList.Any())
                    {
                        var directorIdLinkMap = _appTeamRep.Context.Queryable<SysUser>().Where(u => directorIdLabelList.Contains($"{u.RealName}")).ToList().ToDictionary(u => $"{u.RealName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.DirectorId = directorIdLinkMap.GetValueOrDefault(e.DirectorFkDisplayName ?? "");
                            if (e.DirectorId == null) e.Error = "负责人Id链接失败";
                        });
                    }

                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Status == null)
                        {
                            x.Error = "状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<AppTeam>>();

                    var storageable = _appTeamRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Name), "名称不能为空")
                        .SplitError(it => it.Item.Name?.Length > 64, "名称长度不能超过64个字符")
                        .SplitError(it => it.Item.Slogan?.Length > 256, "口号长度不能超过256个字符")
                        .SplitError(it => it.Item.Avatar?.Length > 512, "队徽长度不能超过512个字符")
                        .SplitError(it => it.Item.ProvinceCode?.Length > 64, "省份长度不能超过64个字符")
                        .SplitError(it => it.Item.DistrictCode?.Length > 64, "区长度不能超过64个字符")
                        .SplitError(it => it.Item.CityCode?.Length > 64, "市长度不能超过64个字符")
                        .SplitError(it => it.Item.Type?.Length > 64, "类型长度不能超过64个字符")
                        .SplitError(it => it.Item.Remark?.Length > 128, "备注长度不能超过128个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();

                    storageable.BulkCopy();
                    storageable.BulkUpdate();

                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });

            return stream;
        }
    }

    /// <summary>
    /// 分页查询球队管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [AllowAnonymous]
    [DisplayName("分页查询球队管理")]
    [ApiDescriptionSettings(Name = "FindPage"), HttpPost]
    public async Task<SqlSugarPagedList<AppTeamOutput>> FindPage(PageAppTeamInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _appTeamRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.TeamName), u => u.Name.Contains(input.TeamName.Trim()))
            .LeftJoin<SysRegion>((u, provinceCode) => u.ProvinceCode == provinceCode.Code)
            .LeftJoin<SysRegion>((u, provinceCode, districtCode) => u.DistrictCode == districtCode.Code)
            .LeftJoin<SysRegion>((u, provinceCode, districtCode, cityCode) => u.CityCode == cityCode.Code)
            .LeftJoin<SysUser>((u, provinceCode, districtCode, cityCode, director) => u.DirectorId == director.Id)
            .Select((u, provinceCode, districtCode, cityCode, director) => new AppTeamOutput
            {
                Id = u.Id,
                Name = u.Name,
                Slogan = u.Slogan,
                Avatar = u.Avatar,
                ProvinceCode = u.ProvinceCode,
                ProvinceCodeFkDisplayName = $"{provinceCode.Name}",
                DistrictCode = u.DistrictCode,
                DistrictCodeFkDisplayName = $"{districtCode.Name}",
                CityCode = u.CityCode,
                CityCodeFkDisplayName = $"{cityCode.Name}",
                RegionId = u.RegionId,
                Code = u.Code,
                Level = u.Level,
                Type = u.Type,
                DirectorId = u.DirectorId,
                DirectorFkDisplayName = $"{director.RealName}",
                OrderNo = u.OrderNo,
                Status = u.Status,
                Remark = u.Remark,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
        return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }



    /// <summary>
    /// 上传球队小程序头像
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("上传球队小程序头像")]
    public async Task<SysFile> UploadTeamAvatar([FromForm] UploadTeamAvatarInput input)
    {

        // 读取上传的文件
        using var imageStream = input.File.OpenReadStream();
        using var image = await Image.LoadAsync(imageStream);

        if (image.Height > 200)
        {
            // 设置新的分辨率（例如：宽度为150，高度按比例缩放）
            int newWidth = 200;
            int newHeight = (int)(image.Height * ((float)newWidth / image.Width));

            // 调整图像分辨率
            image.Mutate(x => x.Resize(newWidth, newHeight));

            // 将处理后的图像保存到内存流
            using var outputStream = new MemoryStream();
            await image.SaveAsync(outputStream, image.Metadata.DecodedImageFormat); // 使用原始图像格式保存

            // 将处理后的图像保存到本地文件（测试用）
            //await using (var testFileStream = File.Create("test_output.jpg"))
            //{
            //    outputStream.Position = 0; // 重置流的位置
            //    await outputStream.CopyToAsync(testFileStream);
            //}

            // 重置流的位置
            outputStream.Position = 0;

            // 将内存流转换为IFormFile
            var processedFile = new FormFile(outputStream, 0, outputStream.Length, input.File.Name, input.File.FileName)
            {
                Headers = input.File.Headers,
                ContentType = input.File.ContentType
            };
            input.File = processedFile;
        }

        var res = await _sysFileService.UploadFile(new UploadFileInput { File = input.File, FileType = input.FileType, SavePath = "upload/team-avatar" });

        return res;
    }

    /// <summary>
    /// 查询球队角色管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("查询球队角色管理")]
    [ApiDescriptionSettings(Name = "FindOneTeamAdmin"), HttpPost]
    public async Task<TeamRoleEnum> FindOneTeamAdmin(QueryByIdAppTeamInput input)
    {
        TeamRoleEnum teamRoleEnum = TeamRoleEnum.Member;
        var query = await _appTeamRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().AsQueryable()
            .Where(u => u.Status == StatusEnum.Enable && u.UserId == _userManager.UserId && u.TeamId == input.Id)
            .FirstAsync();
        if (query!=null)
        {
            if (query.Role == TeamRoleEnum.Admin || query.Role == TeamRoleEnum.Captain)
            {
                teamRoleEnum = query.Role;
            }    
        }
        return teamRoleEnum;
    }

    /// <summary>
    /// 查询是否拥有球队 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("查询是否拥有球队")]
    [ApiDescriptionSettings(Name = "FindOneHasTeamAdmin"), HttpPost]
    public async Task<bool> FindOneHasTeamAdmin(QueryByIdAppTeamInput input)
    {
        bool result = false;
        var query = await _appTeamRep.ChangeRepository<SqlSugarRepository<AppUserTeam>>().AsQueryable()
            .AnyAsync(u => u.Status == StatusEnum.Enable && u.UserId == _userManager.UserId && (u.Role == TeamRoleEnum.Admin || u.Role == TeamRoleEnum.Captain));

        result = true;

        return query;
    }
}
